import { fileServerPath } from '@/config/app.js'
import { Message } from 'element-ui'
export function downloadAttachment(e) {
  if (!e || !e.fileId) return Message.error('文件获取失败')
  let url = srcFormat(e.fileId)
  let name = e.fileName
  if (!/.+\.(jpg|jpeg|gif|bmp|png)$/.test(name)) return download(url, name)
  let image = new Image()
  image.setAttribute('crossOrigin', 'anonymous')
  image.src = url
  image.onload = () => {
    let canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    let ctx = canvas.getContext('2d')
    ctx.drawImage(image, 0, 0, image.width, image.height)
    canvas.toBlob((blob) => {
      let imgUrl = URL.createObjectURL(blob)
      download(imgUrl, name, true)
    })
  }
}
export function download(src, name, open = false) {
  if (open) {
    src && window.open(src)
    return
  }
  const elink = document.createElement('a')
  elink.download = name || '附件'
  elink.setAttribute('download', '')
  elink.style.display = 'none'
  elink.href = src
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href)
  document.body.removeChild(elink)
}
export function srcFormat(value, defaultSrc = '') {
  if (value && value.indexOf('?fid=') === -1 && value.indexOf('http') === -1) {
    return `${fileServerPath}/oss/downloadFile?fid=${value}`
  } else {
    return value || defaultSrc
  }
}
